<?php
/*************************************************************************************
   Copyright notice
   
   (c) 2002-2007 Oliver Georgi (oliver@phpwcms.de) // All rights reserved.
 
   This script is part of PHPWCMS. The PHPWCMS web content management system is
   free software; you can redistribute it and/or modify it under the terms of
   the GNU General Public License as published by the Free Software Foundation;
   either version 2 of the License, or (at your option) any later version.
  
   The GNU General Public License can be found at http://www.gnu.org/copyleft/gpl.html
   A copy is found in the textfile GPL.txt and important notices to the license 
   from the author is found in LICENSE.txt distributed with these scripts.
  
   This script is distributed in the hope that it will be useful, but WITHOUT ANY 
   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
   PARTICULAR PURPOSE.  See the GNU General Public License for more details.
 
   This copyright notice MUST APPEAR in all copies of the script!
*************************************************************************************

   Google Maps Module by breitsch (mail@casa-loca.com)

*************************************************************************************/

function map_url($get='', $type='htmlentities') {
	$base = MODULE_HREF;
	if(is_array($get) && count($get)) {
		$get = implode('&', $get);
	} elseif(empty($get)) {
		$get = '';
	}
	if($get) $get = '&'.$get;
	if(empty($type) || $type != 'htmlentities') {
		$base = str_replace('&amp;', '&', MODULE_HREF);
	} else {
		$get = htmlentities($get);
	}
	return $base.$get;
}

function roundAll($a) {
	$a = floatval($a);
	return round($a, 2);
}

if(!function_exists("bcdiv")){
  function bcdiv($first, $second, $accuracy=2){
    $res = $first/$second;
    return round($res, $accuracy);
  }
}

function listcategories($data_cats, $cat_array_id, $cp_id, $initon, $initzoom, $pid=0, $level=0) {

/*
$data_cats    = all categories from db
$cat_array_id = all active categories (ID's) in this cp
$cp_id        = ID of cp
$initon       = category checked on init, 0=all/1=none/ID 
$pid          = parent category ID, if 0 then no parent
$level        = the level we are in
*/

  $output_cat = "";
  $output_cat_list = "";
  $output_cat_tit = "";
  $get_subcats = "";
  $level++ ;  
  foreach ($data_cats as $key => $value){
      
          switch ($initon) {
            case 0:
              $is_chd = 'checked="checked"';
            break;
            case 1:
              $is_chd = '';
            break;     
            case $data_cats[$key]['cat_id']:
              $is_chd = 'checked="checked"';
            break;         
            default:
              $is_chd = ''; 
            break;
          }
      
      if($data_cats[$key]['cat_pid'] == $pid ) { //top level categories on first loop (when $pid=0)
        
        if(in_array($data_cats[$key]['cat_id'] ,$cat_array_id)) { //if current category is in the cat array of this cp
          //add space before the checkbox
          for ($i=1; $i<$level; $i++) {
            $output_cat_list .= '<span class="spaceBeforeInput">&nbsp;</span>';
          }
          
//          $output_cat_list .= '<input type="checkbox" name="cb_'.$data_cats[$key]['cat_pid'].'_'.$cp_id.'" value="'.$data_cats[$key]['cat_id'].'_'.$cp_id.'" id="cb_'.$data_cats[$key]['cat_id'].'_'.$cp_id.'" '.$is_chd.' onclick="toggleGroup'.$cp_id.'(\''.$data_cats[$key]['cat_id'].'_'.$cp_id.'\', \'false\')" style="vertical-align:middle;" />'."\n";
          $output_cat_list .= '<input type="checkbox" name="cb_'.$data_cats[$key]['cat_pid'].'_'.$cp_id.'" value="'.$data_cats[$key]['cat_id'].'_'.$cp_id.'" id="cb_'.$data_cats[$key]['cat_id'].'_'.$cp_id.'" '.$is_chd.' onclick="toggleGroup(\''.$data_cats[$key]['cat_id'].'_'.$cp_id.'\', \'false\', '.$cp_id.', '.$initzoom.')" style="vertical-align:middle;" />'."\n"; 
          $output_cat_list .= '<label for="cb_'.$data_cats[$key]['cat_id'].'_'.$cp_id.'">'.stripslashes($data_cats[$key]['cat_name']).'</label><br/>';
        }
        //see if we have categories in deeper level
        $get_subcats .= listcategories($data_cats, $cat_array_id, $cp_id, $initon, $initzoom, $data_cats[$key]['cat_id'], $level);
        
        //when we have subcats but the parent is not in the cat array we want this parent nevertheless
        if ($get_subcats) {
          if (!$output_cat_list || $pid==0) {
            $output_cat_list = "";
            for ($i=1; $i<$level; $i++) {
              $output_cat_tit .= '<span class="spaceBeforeInput">&nbsp;</span>';
            } 
 //           $output_cat_tit .= '<input type="checkbox" name="cb_'.$data_cats[$key]['cat_pid'].'_'.$cp_id.'" value="'.$data_cats[$key]['cat_id'].'_'.$cp_id.'" id="cb_'.$data_cats[$key]['cat_id'].'_'.$cp_id.'" '.$is_chd.' onclick="check'.$cp_id.'(\''.$data_cats[$key]["cat_id"].'_'.$cp_id.'\', \'cb_'.$data_cats[$key]["cat_id"].'_'.$cp_id.'\');" style="vertical-align:middle;" />'."\n";
            $output_cat_tit .= '<input type="checkbox" name="cb_'.$data_cats[$key]['cat_pid'].'_'.$cp_id.'" value="'.$data_cats[$key]['cat_id'].'_'.$cp_id.'" id="cb_'.$data_cats[$key]['cat_id'].'_'.$cp_id.'" '.$is_chd.' onclick="check(\''.$data_cats[$key]["cat_id"].'_'.$cp_id.'\', \'cb_'.$data_cats[$key]["cat_id"].'_'.$cp_id.'\', '.$cp_id.', '.$initzoom.');" style="vertical-align:middle;" />'."\n";
            $output_cat_tit .= '<label for="cb_'.$data_cats[$key]['cat_id']."_".$cp_id.'">'.stripslashes($data_cats[$key]['cat_name']).'</label><br/>';
          }
        }
        
        //add the result to the output string (either $output_cat_tit or $output_cat_list is empty)
        $output_cat .= $output_cat_tit.$output_cat_list.$get_subcats;
        $output_cat_list = "";
        $output_cat_tit = "";
        $get_subcats = "";
      }
    }
  return $output_cat;

}

   	/**/
	function gm_get_env_var($Var) {
	  if(empty($GLOBALS[$Var])) {
      $GLOBALS[$Var]=(!empty($GLOBALS['_SERVER'][$Var]))?
 	      $GLOBALS['_SERVER'][$Var]:
  	      (!empty($GLOBALS['HTTP_SERVER_VARS'][$Var]))?
 	          $GLOBALS['HTTP_SERVER_VARS'][$Var]:'';
  	 }
 	}
	
	/**/
	function gm_detect_lang() {
  	// Detect HTTP_ACCEPT_LANGUAGE & HTTP_USER_AGENT.
  	gm_get_env_var('HTTP_ACCEPT_LANGUAGE');
  	gm_get_env_var('HTTP_USER_AGENT');
 	  $_AL=strtolower($GLOBALS['HTTP_ACCEPT_LANGUAGE']);
 	  $_UA=strtolower($GLOBALS['HTTP_USER_AGENT']);
  	// Return language
  	$detected_lang = (!empty($_AL)) ? $_AL : 'en-us';
    return $detected_lang;
  }

function ping_em($sm){
	$pings = array (
	'Google' => 'http://www.google.com/webmasters/sitemaps/ping?sitemap='
);
	$out = '';
	$sm = urlencode($sm);
	foreach($pings as $domain => $val){
		$out .= "<br />";
		if( $reply = & get_content( $val.$sm, true ) ) {
		  if(is_array($reply) ) {
 			$out .= "Pinged <a href=\"{$val}{$sm}\" ><strong>{$domain}</strong></a> said: <br />".preg_replace("#\n+|\s+|<script [^>]+>[^>]+</script>|<[^>]*>#is",' ',chop($reply['content']))."<br />";     
      } else {
  			$out .= "<font color=\"red\">Failed to ping <strong><a href=\"{$val}{$sm}\" >{$domain}</a></strong></font><br />$reply";    
      }
	   }	else{
			  $out .= "<font color=\"red\">Failed to ping <strong><a href=\"{$val}{$sm}\" >{$domain}</a></strong></font><br />";
	   }
	}	
	return $out;
}

/*retrieves urls contents*/
function & get_content($url){
	$fbug = false;
	$cont = array();
		$parse_url = & _parse_url($url);
		clearstatcache();
		if ( ($fp = @fsockopen($parse_url['host'], $parse_url['port'], $errno, $errstr, 15)) === false) {
            switch($errno) {
				case -3:$fbug =  _error( 'Socket creation failed (-3)', 'WARNING');
				case -4:$fbug =  _error( 'DNS lookup failure (-4)', 'WARNING');
				case -5:$fbug =  _error( 'Connection refused or timed out (-5)', 'WARNING');
				default:$fbug =  _error( 'Connection failed ('.$errno.') '.$errstr, 'WARNING');
			}
			return $fbug;
    }
    socket_set_timeout($fp, 15);
		$get = "GET {$parse_url['path']}{$parse_url['query']} HTTP/1.1\r\n";
		$get .= "Host: {$parse_url['host']}\r\n";
		$get .= "Referer: {$parse_url['scheme']}://{$parse_url['host']}{$parse_url['path']}\r\n";
		$get .= "Connection: close\r\n\r\n";
		socket_set_blocking($fp, true);
		fwrite($fp, $get);
		$res = '';
		while ( '' != ($line=trim(fgets($fp, 1024))) ) {
			if ( false !== ($pos=strpos($line, ':')) ) 
				$header[str_replace('-', '_', strtolower(substr($line, 0, $pos)))] = trim(substr($line, $pos+1));
			elseif( preg_match('#\s([0-9]{3})\s#i', $line, $code) )
				$header['http_code'] = intval($code[0]);
		}
		if ( !empty($header['location']) ){
			$cont = & get_content($header['location']);
			$header['http_code'] = 200;
			$header['url'] = $header['location'];
		}
		if (isset($header['transfer_encoding']) && $header['transfer_encoding'] == 'chunked') {
			$chunk = hexdec(fgets($fp, 1024));
		} else {
			$chunk = -1;
		}
		$res = '';
		while ($chunk != 0 && !feof($fp)) {
		    if ($chunk > 0){
		         $part = fread($fp, $chunk);
		         $chunk -= strlen($part);
		         $res .= $part;
		         if ($chunk == 0){
		             if (fgets($fp, 1024) != "\r\n") ;
		             $chunk = hexdec(fgets($fp, 1024));
		         }
		    } else {
		         $res .= fread($fp, 1024);
		    }
		}
		fclose($fp);
		$cont['content'] = $res;
	if(isset($header)){
		if ( isset($header['content_type']) && stripos($header['content_type'], 'text') === false ){
			$fbug = _error("Document type is <strong>{$header['content_type']}</strong> for URL <strong>{$url}</strong>");
			return $fbug;
		}
		if ( isset($header['http_code']) && $header['http_code'] != 200 ){
			$code = "{$header['http_code']}";
			$fbug = _error("<a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.".($code{0}).".".($code{2}+1)."\" target=\"_blank\" ><strong>{$header['http_code']} Error</strong></a> Found for URL <strong>{$url}</strong>", 'WARNING');
			return $fbug;
		}
		if ( isset($header['url']) && $header['url'] != $url ){ #redirection
			$url = $cont['new_url'] = $header['url'];
		}
	}
	return $cont;
}

function & _parse_url(&$url){
	$p = parse_url($url);
	if(!$p)
		return $p;
	$p['host'] = preg_replace('#^(?:www\.)?(.*)$#i', 'www.\\1', $p['host']);
	if ( empty($p['port']) ) {
		if ($p['scheme'] == 'https') {
			$p['port'] = "443";
		} else {
			$p['port'] = "80";
		}
	}
	if ( empty($p['path']) ) {
		$p['path'] = '/';
	}
	#code from http://enarion.net/google/ crawler class
	$query_encoded = '';
	if (!empty($p['query']) ) {
		$query_encoded = '?';
		foreach (split('&', $p['query']) as $id => $quer) {
			$v = split('=', $quer);
			if (!empty($v[1])) {
				$query_encoded .= $v[0].'='.rawurlencode(urldecode($v[1])).'&';
			} else {
				$query_encoded .= $v[0].'&';
			}
		}
		$query_encoded = substr($query_encoded, 0, strlen($query_encoded) - 1);
		$query_encoded = str_replace('%2B','+', $query_encoded);
	}
	$p['query'] = $query_encoded;
	return $p;
}

function _error($msg, $title='NOTICE'){
		$errorMsg = "<div><strong>{$title}: </strong>{$msg}</div>";
	return $errorMsg;
}

function html_parser_googlemaps($string) {
	// parse the $string and replace all possible
	// values with $replace

	if(trim($string) == '') {
		return $string;	
	}

	// page TOP link
	$search[0]		= '/\[TOP\](.*?)\[\/TOP\]/is';
	$replace[0]		= '<a href="#top" class="phpwcmsTopLink">$1</a>';

	// internal Link to article ID
	$search[1]		= '/\[ID (\d+)\](.*?)\[\/ID\]/s';
	$replace[1]		= '<a href="index.php?aid=$1" class="phpwcmsIntLink">$2</a>';

	// external Link (string)
	$search[2]		= '/\[EXT (.*?)\](.*?)\[\/EXT\]/s';
	$replace[2]		= '<a href="$1" target="_blank" class="phpwcmsExtLink">$2</a>';

	// internal Link (string)
	$search[3]		= '/\[INT (.*?)\](.*?)\[\/INT\]/s';
	$replace[3]		= '<a href="$1" class="phpwcmsIntLink">$2</a>';

	// random GIF Image
	$search[4]		= '/\{RANDOM_GIF:(.*?)\}/';
	$replace[4]		= '<img src="img/random_image.php?type=0&imgdir=$1" border="0" alt="" />';

	// random JPEG Image
	$search[5]		= '/\{RANDOM_JPEG:(.*?)\}/';
	$replace[5]		= '<img src="img/random_image.php?type=1&amp;imgdir=$1" border="0" alt="" />';

	// random PNG Image
	$search[6]		= '/\{RANDOM_PNG:(.*?)\}/';
	$replace[6]		= '<img src="img/random_image.php?type=2&amp;imgdir=$1" border="0" alt="" />';

	// insert non db image standard
	$search[7]		= '/\{IMAGE:(.*?)\}/';
	$replace[7]		= '<img src="picture/$1" border="0" alt="" />';

	// insert non db image left
	$search[8]		= '/\{IMAGE_LEFT:(.*?)\}/';
	$replace[8]		= '<img src="picture/$1" border="0" align="left" alt="" />';

	// insert non db image right
	$search[9]		= '/\{IMAGE_RIGHT:(.*?)\}/';
	$replace[9]		= '<img src="picture/$1" border="0" align="right" alt="" />';

	// insert non db image center
	$search[10]		= '/\{IMAGE_CENTER:(.*?)\}/';
	$replace[10]		= '<div align="center"><img src="picture/$1" border="0" alt="" /></div>';

	// insert non db image right
	$search[11]	 	= '/\{SPACER:(\d+)x(\d+)\}/';
	$replace[11] 	= '<img src="img/leer.gif" border="0" width="$1" height="$2" alt="" />';

	// RSS feed link 
	$search[13]		= '/\[RSS (.*?)\](.*?)\[\/RSS\]/s';
	$replace[13]	= '<a href="feeds.php?feed=$1" target="_blank" class="phpwcmsRSSLink">$2</a>';

	// back Link (string)
	$search[14]		= '/\[BACK\](.*?)\[\/BACK\]/i';
	$replace[14] 	= '<a href="#" target="_top" title="go back" onclick="history.back();return false;" class="phpwcmsBackLink">$1</a>';

	// span or div style
	$search[16]		= '/\[(span|div)_style:(.*?)\](.*?)\[\/style\]/s';
	$replace[16]	= '<$1 style="$2">$3</$1>';

	// span or div class
	$search[17]		= '/\[(span|div)_class:(.*?)\](.*?)\[\/class\]/s';
	$replace[17]	= '<$1 class="$2">$3</$1>';

	// typical html formattings

	$search[18]		= '/\[i\](.*?)\[\/i\]/is';			$replace[18]	= '<i>$1</i>';
	$search[19]		= '/\[u\](.*?)\[\/u\]/is';			$replace[19]	= '<u>$1</u>';
	$search[20]		= '/\[s\](.*?)\[\/s\]/is';			$replace[20]	= '<strike>$1</strike>';
	$search[21]		= '/\[b\](.*?)\[\/b\]/is';			$replace[21]	= '<strong>$1</strong>';

	// anchor link
	$search[22]		= '/\{A:(.*?)\}/is';
	$replace[22]	= '<a name="$1" class="phpwcmsAnchorLink"></a>';

	// this parses an E-Mail Link without subject (by Florian, 21-11-2003)
	$search[23]     = '/\[MAIL (.*?)\](.*?)\[\/MAIL\]/is';
	$replace[23]    = '<a href="mailto:$1" class="phpwcmsMailtoLink">$2</a>';

	// this tags out a Mailaddress with an predifined subject (by Florian, 21-11-2003)
	$search[24]     = '/\[MAILSUB (.*?) (.*?)\](.*?)\[\/MAILSUB\]/is';
	$replace[24]    = '<a href="mailto:$1?subject=$2" class="phpwcmsMailtoLink">$3</a>';

	// added simple [br] -> <br />

	$search[25]     = '/\[br\]/i';
	$replace[25]    = '<br />';

	$search[26]     = '/\<br>/i';
	$replace[26]    = '<br />';

	// create "make bookmark" javascript code
	$search[27]     = '/\[BOOKMARK\s{0,}(.*)\](.*?)\[\/BOOKMARK\]/is';
	$replace[27]    = '<a href="#" onclick="BookMark_Page();return false;" title="$1" class="phpwcmsBookmarkLink">$2</a>';

	// ABBreviation
	$search[28]		= '/\[abbr (.*?)\](.*?)\[\/abbr\]/is';
	$replace[28]	= '<abbr title="$1">$2</abbr>';

	$search[29]		= '/\[dfn (.*?)\](.*?)\[\/dfn\]/is';
	$replace[29]	= '<dfn title="$1">$2</dfn>';
/*
	$search[30]		= '/\[em\](.*?)\[\/em\]/is';					$replace[30]	= '<em>$1</em>';
	$search[31]		= '/\[code\](.*?)\[\/code\]/is';				$replace[31]	= '<code>$1</code>';
	$search[32]		= '/\[cite\](.*?)\[\/cite\]/is';				$replace[32]	= '<cite>$1</cite>';
	$search[33]		= '/\[blockquote\](.*?)\[\/blockquote\]/is';	$replace[33]	= '<blockquote>$1</blockquote>';
*/
	$search[34]		= '/\[blockquote (.*?)\](.*?)\[\/blockquote\]/is';
	$replace[34]	= '<blockquote cite="$1">$2</blockquote>';

	$search[35]		= '/\[acronym (.*?)\](.*?)\[\/acronym\]/is';
	$replace[35]	= '<acronym title="$1">$2</acronym>';

	$search[36]		= '/\[ID (.*?)\](.*?)\[\/ID\]/s';
	$replace[36]	= '<a href="index.php?$1" class="phpwcmsIntLink">$2</a>';
/*	
	$search[37]		= '/\[li\](.*?)\[\/li\]/is';					$replace[37]	= '<li>$1</li>';
	$search[38]		= '/\[dt\](.*?)\[\/dt\]/is';					$replace[38]	= '<dt>$1</dt>';
	$search[39]		= '/\[dd\](.*?)\[\/dd\]/is';					$replace[39]	= '<dd>$1</dd>';
	$search[40]		= '/\[ul\](.*?)\[\/ul\]/is';					$replace[40]	= '<ul>$1</ul>';
	$search[41]		= '/\[ol\](.*?)\[\/ol\]/is';					$replace[41]	= '<ol>$1</ol>';
	$search[42]		= '/\[dl\](.*?)\[\/dl\]/is';					$replace[42]	= '<dl>$1</dl>';
	$search[43]		= '/\[h1\](.*?)\[\/h1\]/is';					$replace[43]	= '<h1>$1</h1>';
	$search[44]		= '/\[h2\](.*?)\[\/h2\]/is';					$replace[44]	= '<h2>$1</h2>';
	$search[45]		= '/\[h3\](.*?)\[\/h3\]/is';					$replace[45]	= '<h3>$1</h3>';
	$search[46]		= '/\[h4\](.*?)\[\/h4\]/is';					$replace[46]	= '<h4>$1</h4>';
	$search[47]		= '/\[h5\](.*?)\[\/h5\]/is';					$replace[47]	= '<h5>$1</h5>';
	$search[48]		= '/\[h6\](.*?)\[\/h6\]/is';					$replace[48]	= '<h6>$1</h6>';
*/
	$string = preg_replace($search, $replace, $string);
	$string = str_replace('&#92;&#039;', '&#039;', $string);
	$string = str_replace('&amp;quot;', '&quot;', $string);
	return $string;
}





?>
